<template>
  <view class="account-page">
    <!-- 顶部背景 -->
    <view class="account-header">
      <view class="header-content">
        <view class="back-btn" @click="navigateBack">
          <image class="back-icon" src="/static/Images/wallet/Fanhui.png" mode="aspectFit"></image>
        </view>
        <view class="title">提现</view>
      </view>
    </view>
    
    <!-- 添加支付信息 -->
    <view class="account-content">
      <view class="section-title">{{ paymentMethod === 'wechat' ? '添加微信收款码' : '捆绑支付宝收款账号' }}</view>
      
      <!-- 表单区域 -->
      <view class="form-container">
        <!-- 真实姓名 -->
        <view class="form-item">
          <view class="form-label">真实姓名</view>
          <input 
            class="form-input" 
            type="text" 
            v-model="realName" 
            placeholder="请输入真实姓名"
            placeholder-style="color: #cccccc; font-size: 28rpx;"
          />
        </view>
        
        <!-- 支付宝账号 -->
        <view v-if="paymentMethod === 'alipay'" class="form-item">
          <view class="form-label">支付宝账号</view>
          <input 
            class="form-input" 
            type="text" 
            v-model="alipayAccount" 
            placeholder="请输入支付宝账号"
            placeholder-style="color: #cccccc; font-size: 28rpx;"
          />
        </view>
      </view>
      
      <!-- 收款码上传 (微信和支付宝都需要) -->
      <!-- <view class="qrcode-upload">
        <view v-if="!qrcodeImage" class="upload-container" @click="chooseImage">
          <view class="upload-icon">+</view>
          <view class="upload-text">{{ paymentMethod === 'wechat' ? '上传微信收款码' : '上传支付宝收款码' }}</view>
        </view>
        <view v-else class="preview-container">
          <image class="preview-image" :src="qrcodeImage" mode="aspectFit"></image>
          <view class="remove-btn" @click="removeImage">删除</view>
        </view>
      </view> -->
    </view>
    
    <!-- 保存按钮 -->
    <button type="button" class="save-btn" @click="saveAccount">保存</button>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import { userApi } from '@/utils/api';

// 获取页面参数
const paymentMethod = ref('alipay'); // 默认支付宝，可以从路由参数获取

// 表单数据
const realName = ref('');
const alipayAccount = ref('');
const qrcodeImage = ref('');

// 锁定姓名输入框，禁止聚焦与编辑
const lockRealNameInput = async () => {
  await nextTick();
  try {
    if (typeof document === 'undefined') return; // 非H5平台保护
    const inputs = document.querySelectorAll('.form-item .form-input');
    const inputEl = inputs && inputs[0]; // 第一个输入框为“真实姓名”
    if (inputEl && inputEl.setAttribute) {
      inputEl.setAttribute('readonly', 'readonly');
      inputEl.setAttribute('disabled', 'true');
      // 防止聚焦与交互
      const blurHandler = (e) => {
        try { e.target.blur(); } catch (_) {}
        uni.hideKeyboard && uni.hideKeyboard();
      };
      const prevent = (e) => { e.preventDefault(); };
      inputEl.addEventListener && inputEl.addEventListener('focus', blurHandler, true);
      inputEl.addEventListener && inputEl.addEventListener('click', prevent, true);
      inputEl.addEventListener && inputEl.addEventListener('touchstart', prevent, true);
      inputEl.addEventListener && inputEl.addEventListener('keydown', prevent, true);
    }
  } catch (e) {
    console.warn('锁定姓名输入框失败：', e);
  }
};

// 当 realName 有值（来自 userinfo）后，锁定输入框
watch(realName, (val) => {
  if (val) lockRealNameInput();
});

// 初始化
onMounted(() => {
  // 从页面参数中获取支付方式
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const method = currentPage.options.paymentMethod || currentPage.options.paymentMetho || currentPage.options.method;
  
  if (method) {
    paymentMethod.value = method;
  }

  // 获取用户信息以回填真实姓名（不可修改表单结构，仅赋值）
  fetchUserInfo();
});

// 获取用户信息，回填 real_name
const fetchUserInfo = async () => {
  try {
    const res = await userApi.getUserInfo();
    const data = (res && (res.data?.data ?? res.data ?? res)) || {};
    realName.value = data?.real_name || '';
    if (realName.value) lockRealNameInput();
  } catch (e) {
    console.error('获取用户信息失败：', e);
  }
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      qrcodeImage.value = res.tempFilePaths[0];
    }
  });
};

// 删除图片
const removeImage = () => {
  qrcodeImage.value = '';
};

// 保存账号信息（绑定支付宝）
const saveAccount = async () => {
  // 表单验证
  if (!realName.value) {
    uni.showToast({
      title: '请输入真实姓名',
      icon: 'none'
    });
    return;
  }
  
  if (paymentMethod.value === 'alipay' && !alipayAccount.value) {
    uni.showToast({
      title: '请输入支付宝账号',
      icon: 'none'
    });
    return;
  }
  
  // 注释上传收款码的相关判断
  // if (!qrcodeImage.value) {
  //   uni.showToast({
  //     title: `请上传${paymentMethod.value === 'wechat' ? '微信' : '支付宝'}收款码`,
  //     icon: 'none'
  //   });
  //   return;
  // }

  // 仅在支付宝方式下发起绑定请求
  if (paymentMethod.value === 'alipay') {
    try {
      await userApi.bindAlipay({ real_name: realName.value, alipay: alipayAccount.value });
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1000,
        success: () => {
        }
      });
      uni.showToast({ title: '保存成功', icon: 'success', duration: 1500 });
    } catch (e) {
      uni.showToast({ title: e.message || '保存失败', icon: 'none' });
    }
    return;
  }

  // 非支付宝方式，沿用原回退逻辑
  uni.showToast({
    title: '保存成功',
    icon: 'success',
    duration: 1000,
    success: () => {
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  });
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss">
.account-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 顶部背景 */
.account-header {
  position: relative;
  background-color: #fff;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 1rem;
  padding-bottom: 0.5rem;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  color: #111111;
  font-size: 36rpx;
  font-weight: 500;
  text-align: center;
}

/* 内容区域 */
.account-content {
  margin: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 30rpx;
  padding-left: 10rpx;
}

/* 表单样式 */
.form-container {
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 20rpx;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  width: 180rpx;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  color: #999;
}

/* 收款码上传 */
.qrcode-upload {
  margin-top: 30rpx;
}

.upload-container {
  width: 100%;
  height: 400rpx;
  background-color: #fff;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px solid #f0f0f0;
}

.upload-icon {
  font-size: 80rpx;
  color: #ccc;
  margin-bottom: 20rpx;
  width: 80rpx;
  height: 80rpx;
  line-height: 70rpx;
  text-align: center;
  border: 2rpx dashed #ddd;
  border-radius: 50%;
}

.upload-text {
  font-size: 28rpx;
  color: #999;
}

.preview-container {
  width: 100%;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 400rpx;
  border-radius: 12rpx;
  object-fit: contain;
  background-color: #fff;
  border: 1px solid #f0f0f0;
}

.remove-btn {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

/* 保存按钮 */
.save-btn {
  width: calc(100% - 60rpx);
  height: 90rpx;
  line-height: 90rpx;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 45rpx;
  margin: 60rpx auto 40rpx;
  border: none;
  box-shadow: 0 4rpx 8rpx rgba(255, 77, 79, 0.2);
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
  position: absolute;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
}
</style>